package com.lb.shopguide.ui.fragment.boss.market;

import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.blankj.utilcode.util.ToastUtils;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.SimpleObserverOtherListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.BuildConfig;
import com.lb.shopguide.GuideApplication;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.event.boss.RefreshMyActivityEvent;
import com.lb.shopguide.event.jump.JumpSecretaryEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.shopguide.manager.interf.WebviewInterface;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.dialog.DialogOpenActivitySuccess;
import com.lb.shopguide.ui.fragment.boss.FragmentBossHome;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

public class FragmentActivityApply extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener, WebviewInterface {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.webview)
    BridgeWebView mWebView;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;

    private String applyCode;
    private String msgId;

    private StringBuffer url;

    public static FragmentActivityApply newInstance(String applyCode, String msgId) {
        FragmentActivityApply fragmentActivityApply = new FragmentActivityApply();
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.APPLY_CODE, applyCode);
        bundle.putString(AppConstant.MSG_ID, msgId);
        fragmentActivityApply.setArguments(bundle);
        return fragmentActivityApply;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_activity_apply;
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.APPLY_CODE)) {
            applyCode = bundle.getString(AppConstant.APPLY_CODE);
        }
        if (bundle.containsKey(AppConstant.APPLY_CODE)) {
            msgId = bundle.getString(AppConstant.MSG_ID);
        }
        url = new StringBuffer();
        prepareUrl();
    }

    private void prepareUrl() {
        if (BuildConfig.DEBUG) {
            url.append("https://sintest.storeer.com/boss/sell_template_application_detail?");
            url.append("applyCode=" + applyCode + "&");
            if (!TextUtils.isEmpty(msgId)) {
                url.append("msgId=" + msgId + "&");
            }
//            String userToken = "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJ1c2VyQ29kZSI6ImU3NzhmODBiYzFjYjRlMDliNDA5NWNmMDNiZTcwOWY3IiwiaXNzIjoid2x3YkFwaSIsImF1ZCI6IjdhMTRlNzAxNWQwYTQ5YzZhMzA4Yjk4ZTQwMGYyOWQ4In0.ft6mA5Pg65e8Eayv_KKfECF6RSIp55TJdJJEfo9lSDuxEgNZxWZRPZ6YK0hW4zusZ7a6Nz09gs2VrqzW7CjZcQ";
            url.append("token=" + UserConfigManager.getInstance(GuideApplication.context()).getUserToken() + "&type=android");
        }
    }

    @Override
    public void initView() {
        ntb.setTitleText("活动详情");
        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });

        // 进度条控制
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (isVisible()) {
                    if (newProgress >= 100) {
                        progressBar.setVisibility(View.GONE);
                    } else {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                    super.onProgressChanged(view, newProgress);
                }
            }

        });

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setLightTouchEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setTextSize(WebSettings.TextSize.NORMAL);
//        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setDefaultHandler(new DefaultHandler());
//        mWebView.loadUrl(webUrl);
        mWebView.loadUrl(url.toString());

    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {

    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentActivityApply.class.getName();
    }

    @Override
    public void onRefresh() {

    }

    @OnClick(R.id.tv_refuse)
    void refuseApply() {
        sendRequestOperateApply(AppConstant.APPLY_REFUSE, applyCode);
    }

    @OnClick(R.id.tv_agree)
    void agreeApply() {
        sendRequestOperateApply(AppConstant.APPLY_AGREE, applyCode);
    }

    private void sendRequestOperateApply(final int type, String applyCode) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    if (type == AppConstant.APPLY_REFUSE) {
                        pop();
                        EventBus.getDefault().post(new RefreshMyActivityEvent());
                    } else if (type == AppConstant.APPLY_AGREE) {
                        DialogOpenActivitySuccess dialogOpenActivitySuccess = DialogOpenActivitySuccess.getDialogOpenActivitySuccess();
                        dialogOpenActivitySuccess.show(getFragmentManager(), getPageTag());
                        dialogOpenActivitySuccess.setOnDialogClickListener(new DialogOpenActivitySuccess.OnDialogClickListener() {
                            @Override
                            public void backToHome() {
                                popTo(FragmentBossHome.class, false, new Runnable() {
                                    @Override
                                    public void run() {
                                        EventBus.getDefault().post(new JumpSecretaryEvent());
                                    }
                                });
                            }

                            @Override
                            public void gotoMyActivity() {
                                pop();
                                EventBus.getDefault().post(new RefreshMyActivityEvent());
                            }
                        });
                    }
                }
            }
        };
        SimpleObserverOtherListener errorListener = new SimpleObserverOtherListener() {
            @Override
            public void onSessionOutOfDate() {
                ((GuideMainActivity) getActivity()).onSessionOutOfDate();
            }

            @Override
            public void onError(String error) {
                pop();
                EventBus.getDefault().post(new RefreshMyActivityEvent());
                ToastUtils.showShort(error);
            }
        };
        ApiMethodBoss.checkActivityApplication(new SimpleLbObserver(listener, errorListener), type, applyCode, this, FragmentEvent.DESTROY_VIEW);
    }

    @Override
    public void share() {

    }

    @Override
    public void getBarcode() {

    }

    @Override
    public void call() {

    }

    @Override
    public void savePic() {

    }

    @Override
    public void charge() {

    }

    @Override
    public void backToActivityList() {

    }

    @Override
    public void goToMyActivity() {

    }

    @Override
    public void backToHome() {

    }

    @Override
    public void backToPrePage() {

    }
}
